import time
from DrissionPage import ChromiumPage
from DrissionPage._functions.keys import Keys
from DrissionPage._units.actions import Actions
from pypinyin import lazy_pinyin,load_phrases_dict

# 创建页面对象
'''
返回值：
    返回一个12306页面page对象
'''
def create_page():
    page = ChromiumPage()
    page.get('https://www.12306.cn/index/')
    return page

# 登入函数
'''
参数：
    页面对象
返回值：
    登入的页面对象page
'''
def login_page(page):
    try:
        page.ele('x:.//a[@id="J-btn-login"]').click()
        time.sleep(1)
        page.ele('x:.//div[@class="login-box"]/ul/li[@class="login-hd-account"]/a').click()
        # 进行扫码登入
        while '扫码登录' in page.active_ele.html:
            print('扫码登入')
            time.sleep(10)
        print('登入成功')
        time.sleep(1)
    except:
        print('已近登入')
        Actions(page).move_to(page.ele('x:.//li[@id="J-header-logout"]/a[@name="g_href"]')).click()
        time.sleep(3)
        page.ele('x:.//li[@id="gerenzhongxin"]/h2/a').click()
        time.sleep(3)
    return page                                   # 返回登入的页面对象

# 显示登入信息
def geren_info(page):
    name = page.ele('x:.//div[@class="welcome-tit"]/strong[@class="welcome-name"]').text
    print(f'登入用户：{name}')

# 拼音处理函数
"""
参数：中文（str）
返回值：拼音（str）
"""
def pinyin_cl(char):
    # 创建一个字典用来处理多音字
    dict_citys = {
        "长治": [["chángzhì"]],
    }
    load_phrases_dict(dict_citys)                  # 加载字典
    char = ''.join(lazy_pinyin(char))
    char = char.replace(' ','')
    return char

# 下拉框参数获取函数


# 查询车票
"""
参数：
    1.页面对象
    2.出发车站（from_station）
    3.到站车站（end_station）
返回参数（list）：
"""
def query_ticket(page,from_station,end_station,time_station_from,time_station_end):
    # 定义返回数据
    query_ticket_lists = []
    # 进入车票查询页面
    page.ele('x:.//a[@id="link_for_ticket"]').click()
    # 获取标签
    fromStationText_tag = page.ele('#fromStationText')       # 出发地
    toStationText_tag = page.ele('#toStationText')           # 目的地
    # 获取地址拼音
    from_station_py = pinyin_cl(from_station)
    to_station_py = pinyin_cl(end_station)
    # 实例化动作对象
    actions_page = Actions(page)

    # 出发地进行输入
    actions_page.move_to(fromStationText_tag).click().type(from_station_py)
    # 获取下拉框
    cities = page.eles('x:.//div[@id="panel_cities"]/div')  # 下拉框
    for city in cities:
        city_name = city.ele('x:./span[@class="ralign"]').text
        if city_name == from_station:
            city.click()
    # 目的地输入
    actions_page.move_to(toStationText_tag).type(to_station_py)
    # 获取下拉框
    cities = page.eles('x:.//div[@id="panel_cities"]/div')  # 下拉框
    for city in cities:
        city_name = city.ele('x:./span[@class="ralign"]').text
        if city_name == end_station:
            city.click()

    # 时间输入
    print('开始输入时间')
    page.ele('x:.//input[@id="train_date"]').clear().input(time_station_from)
    page.ele('x:.//input[@id="back_train_date"]').clear().input(time_station_end)
    # actions_page.move_to(page.ele('x:.//input[@id="train_date"]')).type(time_station_from).key_down('ENTER')
    # actions_page.move_to(page.ele('x:.//input[@id="back_train_date"]')).type(time_station_end).key_down('ENTER')

    # 点击查询
    page.ele('x:.//a[@id="query_ticket"]').click()
    time.sleep(2)

    # 获取车票信息
    ticket_tags = page.eles('x:.//tbody[@id="queryLeftTable"]/tr[@class="" or @class="bgc"]')
    for ticket in ticket_tags:
        try:
            cc = ticket.ele('x:.//td[@colspan="4"]/div/div[@class="train"]/div/a').text                     # 车次
        except:
            print('车票已经获取完成')
            break
        cdz_start_s = ticket.eles('x:.//td[@colspan="4"]/div/div[@class="cdz"]/strong')[0].text         # 出发站
        cdz_end_s = ticket.eles('x:.//td[@colspan="4"]/div/div[@class="cdz"]/strong')[1].text           # 终点站
        cds = ticket.ele('x:.//td[@colspan="4"]/div/div[@class="cds"]/strong[@class="start-t"]').text   # 出发时间
        ls = ticket.ele('x:.//td[@colspan="4"]/div/div[@class="ls"]').text                              # 到站时间
        zuoweis = ticket.eles('x:.//td[@width="46"]')
        shangwu = zuoweis[0].text                                # 商务座
        one_yzw = zuoweis[1].text                                # 优选一等座
        one_zw = zuoweis[2].text                                 # 一等座
        two_bzw = zuoweis[3].text                                # 二等包座
        gaoji_rw = zuoweis[4].text                               # 高级软卧
        ry_one_zw = zuoweis[5].text                              # 软卧/动卧一等卧
        yw_two_zw = zuoweis[6].text                              # 硬卧二等卧
        r_zw = zuoweis[7].text                                   # 软座
        y_zw = zuoweis[8].text                                   # 硬座
        wu_zw = zuoweis[9].text                                  # 无座
        qi_zw = zuoweis[10].text                                 # 其他
        yuding_button = ticket.ele('x:.//td[@width="80"]/a')                  # 点击标签
        print(f'车次:{cc},出发站:{cdz_start_s},终点站:{cdz_end_s},出发时间:{cds},到站时间:{ls},商务座:{shangwu},优选一等座:{one_yzw},一等座:{one_zw},二等包座:{two_bzw},高级软卧:{gaoji_rw},软卧/动卧一等卧:{ry_one_zw},硬卧二等卧:{yw_two_zw},软座:{r_zw},硬座:{y_zw},无座:{wu_zw},其他:{qi_zw},点击标签:{yuding_button}')
        print('-------------------------------------------------------------------------------------')
        # 定义车票字典
        # dict_ticket = {'车次':cc,'出发站':cdz_start_s,'终点站':cdz_end_s,'出发时间':cds,'到站时间':ls,'商务座':shangwu,'优选一等座':one_yzw,'一等座':one_zw,'二等包座':two_bzw,'高级软卧':gaoji_rw,'软卧/动卧一等卧':ry_one_zw,'硬卧二等卧':yw_two_zw,'软座':r_zw,'硬座':y_zw,'无座':wu_zw,'其他':qi_zw,'点击标签':yuding_button}
        dict_ticket = {'车次':cc,'点击标签':yuding_button}
        query_ticket_lists.append(dict_ticket)

    return query_ticket_lists




if __name__ == '__main__':
    page = create_page()
    page = login_page(page)                   # 进行登入
    geren_info(page)                          # 显示登入的信息
    list1 = query_ticket(page,'长治','太古','2025-05-23','2025-05-23')

    # ---------------------------------------------------------------------------------------------------
    # 查询购票信息代码测试
    # page = ChromiumPage()
    # page.get('https://kyfw.12306.cn/otn/leftTicket/init')
    # from_station = '长治'
    # end_station = '太谷'
    # query_ticket_cs(page,from_station,end_station)

    # ---------------------------------------------------------------------------------------------------
    # 拼音代码测试
    # pinyin_cl('中文')